<?php

	/*
	Revised code by Dominick Lee
	Original code derived from "Essential PHP Security" by Chriss Shiflett
	Last Modified 2/27/2017


	CREATE TABLE sessions
	(
		id varchar(32) NOT NULL,
		access int(10) unsigned,
		data text,
		PRIMARY KEY (id)
	);

	+--------+------------------+------+-----+---------+-------+
	| Field  | Type             | Null | Key | Default | Extra |
	+--------+------------------+------+-----+---------+-------+
	| id     | varchar(32)      |      | PRI |         |       |
	| access | int(10) unsigned | YES  |     | NULL    |       |
	| data   | text             | YES  |     | NULL    |       |
	+--------+------------------+------+-----+---------+-------+

	*/
define("DB_HOST", $dbhost);
define("DB_USER", $dbuser);
define("DB_PASS", $dbpwd );
define("DB_NAME", $dbName);
class Session {
	private $db;

	public function __construct(){
		// Instantiate new Database object
		$this->db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

		// Set handler to overide SESSION
		session_set_save_handler(
		array($this, "_open"),
		array($this, "_close"),
		array($this, "_read"),
		array($this, "_write"),
		array($this, "_destroy"),
		array($this, "_gc")
		);
 
		// Start the session
		session_start();
	}
	public function _open(){
 
		// If successful
		if($this->db){
		// Return True

		return true;
		}
		// Return False
		return false;
	}
	public function _close(){
		// Close the database connection
		// If successful
		if($this->db->close()){
		// Return True
		return true;
		}
		// Return False
		return false;
	}
	public function _read($id){
		// Set query
		$query=$this->db->query('SELECT data FROM sessions WHERE id = "'.$id.'" limit 0,1');
		$row=$query->fetch_assoc();
		if (isset($row['data'])) {
			$data=$row['data'];
		    // Return the data
		    return (string)$data;
		}
		
		return '';
		
	}
	public function _write($id, $data){
		// Create time stamp
		$access = time();
		
		$query=$this->db->query('SELECT id FROM `sessions` where  id="'.$id.'"');
        if($query->num_rows>0){
            $query=$this->db->query('update sessions set access="'.$access.'", data="'.addslashes($data).'" where  id="'.$id.'"');
        }else{
        	$query=$this->db->query('insert into sessions(id,access,data) VALUES ("'.$id.'", '.$access.', "'.addslashes($data).'")');
        }

		// Set query  
		
		 
		return true;
		 
	}
	public function _destroy($id){
		// Set query
		$this->db->query('DELETE FROM sessions WHERE id = "'.$id.'"');
		// Bind data
		
		return true; 

		//if($this->db->execute()){return true;}
		// Return False
		//return false;
	} 
	public function _gc($max){
		// Calculate what is to be deemed old
		$old = time() - $max;
		// Set query
		$this->db->query('DELETE FROM sessions WHERE access < '.$old);
		// Bind data
		//$this->db->bind(':old', $old);
		
		return true;
		
	}
}
?>